import { saveProof } from '@/services/api/api-assess-week-culture-proof';
import { treeSource } from '@/services/api/api-assess-week-culture-source';
import { CheckCircleOutlined, CheckCircleTwoTone } from '@ant-design/icons';
import {
  ModalForm,
  ProFormCascader,
  ProFormDatePicker,
  ProFormDigit,
  ProFormTextArea
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Alert, Button, message, Spin, Typography } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import UploadDragger from '../components/UploadDragger';
import UploadImage from '../components/UploadImage';
import UploadVideo from '../components/UploadVideo';

interface AddProofProps {
  areaId: string;
  areaName: string;
  releaseTimes: Array<string>; //季度发布时间范围
  onRefurbish: () => void;
}

const AddProof: React.FC<AddProofProps> = ({ areaId, areaName, releaseTimes, onRefurbish }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  /**
   * 提交窗口
   */
  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 初始化Cascader数据
   */

  const [dataSource, setDataSourceState] = useState<any>();

  /**
   * 选择 Cascader数据 来源
   */
  const [selectSourceCascader, setSelectSourceCascaderState] = useState<string[]>([]);
  /**
   * 选择 Cascader数据 来源
   */
  const [selectSource, setSelectSourceState] = useState<any>();

  /**
   * 控制修改分数
   */

  const [showChangeScore, setShowChangeScoreState] = useState<boolean>(false);

  /**
   * 预备Cascader结构数据
   * @param data
   */
  function readyCascaderData(data: AssessWeekCultureSourceData.Source[]): any {
    const cascaderData = new Array();
    if (data) {
      data.forEach((val) => {
        cascaderData.push({
          label: `${val.name}${val.score !== null ? `（${val.score}分）` : ''}`,
          value: val.id,
          describes: val.describes,
          score: val.score,
          source: val,
          children: readyCascaderData(val.children as AssessWeekCultureSourceData.Source[]),
        });
      });
    }
    return cascaderData;
  }

  /**
   * 加载来源详情
   * @param key
   */
  const loadSourceData = async () => {
    try {
      const response = await treeSource();
      if (response.code === 0) {
        const CascaderData = readyCascaderData(response.data);
        setDataSourceState(CascaderData);
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      key="add_assess_record_drawer_form"
      title={'新建记录'}
      drawerProps={{
        width: 660,
        maskClosable: false,
        destroyOnClose: true,
      }}
      layout="horizontal"
      formRef={formRef}
      trigger={<Button type="primary">新建记录</Button>}
      initialValues={{}}
      onOpenChange={(visible) => {
        if (visible) {
          loadSourceData();
        } else {
          setSelectSourceState(undefined);
          setShowChangeScoreState(false);
        }
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              key="button_release_state_discard"
              icon={<CheckCircleOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                const values = formRef.current?.getFieldsValue();

                if (!(values.sourceIds !== undefined && values.sourceIds.length > 0)) {
                  message.warning('请选择来源');
                  return;
                }

                if (values.releaseTime === undefined) {
                  message.warning('请选择日期');
                  return;
                }

                if (!(values.name !== undefined && values.name.length > 0)) {
                  message.warning('请输入标题');
                  return;
                }

                if (values.name.length > 60) {
                  message.warning('标题长度超过限制');
                  return;
                }

                if (
                  selectSource !== undefined &&
                  (selectSource.source.datahubChannelName === '电子报纸' ||
                    selectSource.source.datahubChannelName === '客户端' ||
                    selectSource.source.datahubChannelName === '网站')
                ) {
                  const placeholder =
                    selectSource.source.datahubChannelName === '电子报纸'
                      ? '电子报封面'
                      : selectSource.source.datahubChannelName === '客户端' ||
                        selectSource.source.datahubChannelName === '网站'
                      ? '首页、首屏截图'
                      : '';

                  if (values.attachmentSnapshots === undefined) {
                    message.warning(`请上传${placeholder}`);
                    return;
                  }

                  if (values.attachmentSnapshots && values.attachmentSnapshots.length > 0) {
                    let attachmentSnapshots = new Array();

                    values.attachmentSnapshots.forEach((item: any) => {
                      if (item.status === 'done') {
                        attachmentSnapshots.push({
                          id: item.response.data.id,
                        });
                      }
                    });

                    if (attachmentSnapshots.length === 0) {
                      if (values.attachmentSnapshots === undefined) {
                        message.warning(`请上传有效的${placeholder}`);
                        return;
                      }
                      return;
                    }

                    values.attachmentSnapshots = attachmentSnapshots;
                  }
                }

                if (
                  selectSource !== undefined &&
                  selectSource.source.datahubChannelName === '电视视频'
                ) {
                  const placeholder = '电视视频';

                  if (values.attachmentVideos === undefined) {
                    message.warning(`请上传${placeholder}`);
                    return;
                  }

                  if (values.attachmentVideos && values.attachmentVideos.length > 0) {
                    let attachmentVideos = new Array();

                    values.attachmentVideos.forEach((item: any) => {
                      if (item.status === 'done') {
                        attachmentVideos.push({
                          id: item.response.data.id,
                        });
                      }
                    });

                    if (attachmentVideos.length === 0) {
                      if (values.attachmentVideos === undefined) {
                        message.warning(`请上传有效的${placeholder}`);
                        return;
                      }
                      return;
                    }

                    values.attachmentVideos = attachmentVideos;
                  }
                }

                if (values.attachmentOthers && values.attachmentOthers.length > 0) {
                  let attachmentOthers = new Array();

                  values.attachmentOthers.forEach((item: any) => {
                    if (item.status === 'done') {
                      attachmentOthers.push({
                        id: item.response.data.id,
                      });
                    }
                  });

                  if (attachmentOthers.length === 0) {
                    if (values.attachmentOthers === undefined) {
                      message.warning('请上传有效的凭证附件');
                      return;
                    }
                    return;
                  }

                  values.attachmentOthers = attachmentOthers;
                }
                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_release_state_discard'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async (values) => {
                props.submit();
                return true;
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        if (!(values.sourceIds !== undefined && values.sourceIds.length > 0)) {
          message.warning('请选择来源');
          return;
        }

        if (values.releaseTime === undefined) {
          message.warning('请选择日期');
          return;
        }

        if (!(values.name !== undefined && values.name.length > 0)) {
          message.warning('请输入标题');
          return;
        }

        if (values.name.length > 60) {
          message.warning('标题长度超过限制');
          return;
        }

        if (
          selectSource !== undefined &&
          (selectSource.source.datahubChannelName === '电子报纸' ||
            selectSource.source.datahubChannelName === '客户端' ||
            selectSource.source.datahubChannelName === '网站')
        ) {
          const placeholder =
            selectSource.source.datahubChannelName === '电子报纸'
              ? '电子报封面'
              : selectSource.source.datahubChannelName === '客户端' ||
                selectSource.source.datahubChannelName === '网站'
              ? '首页、首屏截图'
              : '';

          if (values.attachmentSnapshots === undefined) {
            message.warning(`请上传${placeholder}`);
            return;
          }

          if (values.attachmentSnapshots && values.attachmentSnapshots.length > 0) {
            let attachmentSnapshots = new Array();

            values.attachmentSnapshots.forEach((item: any) => {
              if (item.status === 'done') {
                attachmentSnapshots.push({
                  id: item.response.data.id,
                });
              }
            });

            if (attachmentSnapshots.length === 0) {
              if (values.attachmentSnapshots === undefined) {
                message.warning(`请上传有效的${placeholder}`);
                return;
              }
              return;
            }

            values.attachmentSnapshots = attachmentSnapshots;
          }
        }

        if (selectSource !== undefined && selectSource.source.datahubChannelName === '电视视频') {
          const placeholder = '电视视频';

          if (values.attachmentVideos === undefined) {
            message.warning(`请上传${placeholder}`);
            return;
          }

          if (values.attachmentVideos && values.attachmentVideos.length > 0) {
            let attachmentVideos = new Array();

            values.attachmentVideos.forEach((item: any) => {
              if (item.status === 'done') {
                attachmentVideos.push({
                  id: item.response.data.id,
                });
              }
            });

            if (attachmentVideos.length === 0) {
              if (values.attachmentVideos === undefined) {
                message.warning(`请上传有效的${placeholder}`);
                return;
              }
              return;
            }

            values.attachmentVideos = attachmentVideos;
          }
        }

        if (values.attachmentOthers && values.attachmentOthers.length > 0) {
          let attachmentOthers = new Array();

          values.attachmentOthers.forEach((item: any) => {
            if (item.status === 'done') {
              attachmentOthers.push({
                id: item.response.data.id,
              });
            }
          });

          if (attachmentOthers.length === 0) {
            if (values.attachments === undefined) {
              message.warning('请上传有效的凭证附件');
              return;
            }
            return;
          }

          values.attachmentOthers = attachmentOthers;
        }

        const response = await saveProof({
          areaId: areaId,
          ...values,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          // return true;
        } else {
          return false;
        }
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={dataSource === undefined}
      >
        {dataSource !== undefined && (
          <>
            <ProFormCascader
              width="xl"
              name="sourceIds"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  来源
                </>
              }
              fieldProps={{
                displayRender: (labels: string[], selectedOptions?: any[]) => {
                  return labels.map((label, i) => {
                    if (selectedOptions) {
                      const option = selectedOptions[i];
                      if (i === labels.length - 1) {
                        /**
                         * 1、赋值来源
                         *
                         * 2、清除其他选项数据
                         */
                        setSelectSourceState(option);
                        formRef.current?.setFieldsValue({
                          applyScore: option.score,
                        });

                        return <span key={option.value}>{label}</span>;
                      }
                      return <span key={option.value}>{label} / </span>;
                    } else {
                      return '';
                    }
                  });
                },
                onChange: (values: any) => {
                  if (values === undefined) {
                    setSelectSourceState(undefined);
                    setSelectSourceCascaderState([]);
                    formRef.current?.setFieldsValue({
                      applyScore: '',
                    });
                    /**
                     * 2、清除其他选项数据
                     */
                    formRef.current?.setFieldsValue({
                      releaseTime: undefined,
                      name: '',
                      url: '',
                      attachmentSnapshots: [],
                      remarks: '',
                      attachments: [],
                    });
                  } else {
                    if (values.at(-1) !== selectSourceCascader.at(-1)) {
                      setSelectSourceCascaderState(values);
                      /**
                       * 2、清除其他选项数据
                       */
                      formRef.current?.setFieldsValue({
                        releaseTime: undefined,
                        name: '',
                        url: '',
                        attachmentSnapshots: [],
                        remarks: '',
                        attachments: [],
                      });
                    }
                  }
                },
                options: dataSource,
                allowClear: true,
              }}
            />
            <ProFormDigit
              width="md"
              name="applyScore"
              label={
                <span
                  style={{
                    marginLeft: 11,
                  }}
                >
                  申请
                </span>
              }
              min={1}
              max={500}
              hidden={!showChangeScore}
              fieldProps={{
                maxLength: 200,
              }}
              addonAfter={
                <a
                  style={{
                    color: '#ff4d4f',
                  }}
                  onClick={() => {
                    formRef.current?.setFieldsValue({
                      applyScore: '',
                    });
                    setShowChangeScoreState(false);
                  }}
                >
                  关闭
                </a>
              }
            />
            {selectSource !== undefined && (
              <>
                {selectSource?.score !== null && (
                  <div
                    style={{
                      marginLeft: 52.05,
                      marginBottom: 25,
                    }}
                  >
                    <Alert
                      message={
                        <>
                          根据要求所得分数为：{selectSource?.score}
                          {/* ，如有特殊申请可点击
                          <a
                            onClick={() => {
                              setShowChangeScoreState(true);
                            }}
                          >
                            修改分数
                          </a> */}
                        </>
                      }
                      type="success"
                      showIcon
                    />
                  </div>
                )}
                <Typography
                  style={{
                    marginBottom: '14px',
                  }}
                >
                  {selectSource?.describes !== null && (
                    <Typography.Paragraph
                      style={{
                        marginLeft: 52.05,
                        marginBottom: 25,
                      }}
                    >
                      <blockquote>{selectSource?.describes}</blockquote>
                    </Typography.Paragraph>
                  )}
                </Typography>
              </>
            )}
            <ProFormDatePicker
              width="md"
              name="releaseTime"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  日期
                </>
              }
              extra={
                <>
                  选择范围 {dayjs(releaseTimes[0]).format('YYYY/MM/DD')} -
                  {dayjs(releaseTimes[1]).format('YYYY/MM/DD')}
                </>
              }
              fieldProps={{
                format: 'YYYY-MM-DD',
                allowClear: true,
                disabledDate: (current) => {
                  return (
                    current &&
                    (current < dayjs(releaseTimes[0]) || current > dayjs(releaseTimes[1]))
                  );
                },
                showToday: false,
              }}
            />
            {/* <Alert
              message={`日期选择范围（${dayjs(ledger?.startTime).format('YYYY/MM/DD')} - ${dayjs(
                ledger?.endTime,
              ).format('YYYY/MM/DD')}）`}
              type="success"
              showIcon
            /> */}
            <ProFormTextArea
              width="xl"
              name="name"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  标题
                </>
              }
              fieldProps={{
                showCount: true,
                allowClear: true,
                // maxLength: 200,
                rows: 2,
                // size: 'large',
                count: { show: true, max: 60 },
                style: { resize: 'none' },
              }}
            />
            {selectSource !== undefined &&
              selectSource.source.datahubChannelName === '电子报纸' && (
                <>
                  <div
                    style={{
                      width: 552,
                      marginLeft: 52.05,
                      marginBottom: 25,
                    }}
                  >
                    <Alert
                      message="为保证记录被正确采纳，请尽量填写相关信息，包括链接、封面、备注"
                      type="warning"
                      showIcon
                    />
                  </div>
                  <ProFormTextArea
                    width="xl"
                    name="url"
                    label={
                      <span
                        style={{
                          marginLeft: 11,
                        }}
                      >
                        链接
                      </span>
                    }
                    fieldProps={{
                      allowClear: true,
                      rows: 3,
                      count: { show: true, max: 5000 },
                      placeholder: selectSource.source.datahubSourceCharacteristics,
                    }}
                  />

                  <FormItem
                    name="attachmentSnapshots"
                    label={
                      <span
                        style={{
                          marginLeft: 11,
                        }}
                      >
                        封面
                      </span>
                    }
                    hidden={!access.文化报表x创建x附件}
                  >
                    <UploadImage
                      onPreview={(file) => {}}
                      access={{
                        isPicture: access.文化报表x创建x附件x图片,
                      }}
                      url="/assess/culture/attachment/save"
                      maxCount={2}
                      placeholder="电子报封面"
                    />
                  </FormItem>
                </>
              )}
            {selectSource !== undefined &&
              selectSource.source.datahubChannelName === '电视视频' && (
                <>
                  <div
                    style={{
                      width: 552,
                      marginLeft: 52.05,
                      marginBottom: 25,
                    }}
                  >
                    <Alert
                      message="为保证记录被正确采纳，请尽量填写相关信息，包括链接、片段、备注"
                      type="warning"
                      showIcon
                    />
                  </div>
                  <ProFormTextArea
                    width="xl"
                    name="url"
                    label={
                      <span
                        style={{
                          marginLeft: 11,
                        }}
                      >
                        链接
                      </span>
                    }
                    fieldProps={{
                      allowClear: true,
                      rows: 3,
                      count: { show: true, max: 5000 },
                      placeholder: selectSource.source.datahubSourceCharacteristics,
                    }}
                  />
                  <FormItem
                    name="attachmentVideos"
                    label={
                      <span
                        style={{
                          marginLeft: 11,
                        }}
                      >
                        片段
                      </span>
                    }
                    hidden={!access.文化报表x创建x附件}
                  >
                    <UploadVideo
                      onPreview={(file) => {}}
                      access={{
                        isVideo: access.文化报表x创建x附件x视频,
                      }}
                      url="/assess/culture/attachment/save"
                      maxCount={2}
                      placeholder="播报视频片段"
                    />
                  </FormItem>
                </>
              )}

            {selectSource !== undefined &&
              (selectSource.source.datahubChannelName === '客户端' ||
                selectSource.source.datahubChannelName === '网站') && (
                <>
                  <div
                    style={{
                      width: 552,
                      marginLeft: 52.05,
                      marginBottom: 25,
                    }}
                  >
                    <Alert
                      message="为保证记录被正确采纳，请尽量填写相关信息，包括链接、首页截图、首屏截图、备注"
                      type="warning"
                      showIcon
                    />
                  </div>
                  <ProFormTextArea
                    width="xl"
                    name="url"
                    label={
                      <span
                        style={{
                          marginLeft: 11,
                        }}
                      >
                        链接
                      </span>
                    }
                    fieldProps={{
                      allowClear: true,
                      rows: 3,
                      count: { show: true, max: 5000 },
                      placeholder: selectSource.source.datahubSourceCharacteristics,
                    }}
                  />
                  <FormItem
                    name="attachmentSnapshots"
                    label={
                      <span
                        style={{
                          marginLeft: 11,
                        }}
                      >
                        封面
                      </span>
                    }
                    hidden={!access.文化报表x创建x附件}
                  >
                    <UploadImage
                      onPreview={(file) => {}}
                      access={{
                        isPicture: access.文化报表x创建x附件x图片,
                      }}
                      url="/assess/culture/attachment/save"
                      maxCount={2}
                      placeholder="首页、首屏截图"
                    />
                  </FormItem>
                </>
              )}
            <ProFormTextArea
              width="xl"
              name="remarks"
              label={
                <span
                  style={{
                    marginLeft: 11,
                  }}
                >
                  备注
                </span>
              }
              fieldProps={{
                allowClear: true,
                rows: 3,
                count: { show: true, max: 5000 },
              }}
            />
            <FormItem
              name="attachmentOthers"
              label={
                <span
                  style={{
                    marginLeft: 11,
                  }}
                >
                  附件
                </span>
              }
              hidden={!access.文化报表x创建x附件}
            >
              <UploadDragger
                onPreview={(file) => {}}
                access={{
                  isPicture: access.文化报表x创建x附件x图片,
                  isVideo: access.文化报表x创建x附件x视频,
                  isOffice: access.文化报表x创建x附件x办公,
                  isOther: access.文化报表x创建x附件x其他,
                }}
                url="/assess/culture/attachment/save"
                maxCount={2}
              />
            </FormItem>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default AddProof;
